<?php
if(isset($__ts)) unset($__ts);
$__ts = array();

global $blog, $service, $__ts;

# Locale language file support, defualt is en-us.php
if (!isset($blog['blogLanguage'])) {
	$blog['blogLanguage'] = $service['language'];
}
// Locale language file support.
switch($blog['blogLanguage']) {
	case "zh-TW":
	case "zh-CN":
		$languageFile = 'lang/'.$blog['blogLanguage'].'.php';
		$imgLang = '.'.$blog['blogLanguage'];
	break;
	default:
		$languageFile = "";
		$imgLang = '';
}
if(!empty($languageFile)) { include_once ($languageFile); }

function getMediaSearchViewToolbox($target){
	global $blogURL, $pluginURL, $serviceURL, $service;
	requireComponent('Textcube.Function.misc');
	ob_start();
	?>
	<img src="<?php echo $pluginURL;?>/images/flickr_n_youtube_SearchIcon.gif" border="0" onclick="photoNmediaSearchPop();" style="cursor:pointer;" />
	<?php
	$html = ob_get_contents();
	ob_end_clean();
	return $target.$html;
}

function getMediaSearchViewScriptStyle($target) {
	global $blog, $service, $blogURL, $pluginURL, $serviceURL, $service, $suri;
	
	if (!isset($blog['blogLanguage'])) {
		$blog['blogLanguage'] = $service['language'];
	}
	switch($blog['blogLanguage']) {
		case "zh-TW":
		case "zh-CN":
		case "en":
			$imgLang = '.'.$blog['blogLanguage'];
		break;
		default:
			$imgLang = '';
	}
	
	$html = '';
	if ($suri['directive'] == '/owner/entry/post' || $suri['directive'] == '/owner/entry/edit') {
		requireComponent('Textcube.Function.misc');
		$tempPath = getTempPath();
		ob_start();
		?>
		<script type="text/javascript" src="<?php echo $service['path'].$tempPath['script'];?>/dojo/dojo.js"></script>
		<script type="text/javascript">
		//<![CDATA[
			var loginCheckFlag = 0;
			function initPages(){
				dlg = dojo.widget.createWidget("popupWindow", {}, document.getElementById("body-entry").firstChild, "after");
				dlg.domNode.className = "ajax-popup-window";
			}
			dojo.addOnLoad(initPages);
		//]]>
		</script>
		<script type="text/javascript" src="<?php echo $pluginURL?>/script/plugin-main.js"></script>
		<style type="text/css">
			.mediaFlickrLogoSelected {
				width:130px; height:24px;
				background:url('<?php echo $pluginURL?>/images/flickrSearchTabIcon<?php echo $imgLang;?>.gif')  no-repeat 0px -24px #1D3053;
			}
			.mediaFlickrLogoUnselected {
				width:130px; height:24px;
				background:url('<?php echo $pluginURL?>/images/flickrSearchTabIcon<?php echo $imgLang;?>.gif')  no-repeat 0px 0px #1D3053;
			}
			.mediaYoutubeLogoSelected {
				width:130px; height:24px;
				background:url('<?php echo $pluginURL?>/images/youtubeSearchTabIcon<?php echo $imgLang;?>.gif')  no-repeat 0px -24px #1D3053;
			}
			.mediaYoutubeLogoUnselected {
				width:130px; height:24px;
				background:url('<?php echo $pluginURL?>/images/youtubeSearchTabIcon<?php echo $imgLang;?>.gif')  no-repeat 0px 0px #1D3053;
			}
		</style>
		<?php
		$html = ob_get_contents();
		ob_end_clean();
	}
	return $target.$html;
}

function getMediaSearchView($target) {
	global $blogURL, $service, $__ts;
	if(!class_exists('pluginLocal')) require_once ('lang/pluginLocal.php');
	
	$tempPath = getTempPath();
	$phpVersion = phpversion();
	ob_start();
	?>
	<div class="mediaSearchTabBar">
		<div class="mediaSearchTab">
			<div class="mediaFlickrTab"><img <?php echo ($phpVersion < 4.2 ? ' onclick="alert(\''.pluginLang::plts('Flickr 메뉴는 PHP 버전이 낮아 사용할 수 없습니다.').'  \');" ' : ' onclick="mediaSelectedTab(\'Flickr\', \'Youtube\');" ');?> id="mediaFlickrLogo" class="<?php echo ($phpVersion < 4.2 ? 'mediaFlickrLogoUnselected' : 'mediaFlickrLogoSelected');?>" src="<?php echo $service['path'].$tempPath['image'];?>/spacer.gif" border="0" /></div>
			<div class="mediaYoutubeTab"><img onclick="mediaSelectedTab('Youtube', 'Flickr');" id="mediaYoutubeLogo" class="<?php echo ($phpVersion < 4.2 ? 'mediaYoutubeLogoSelected' : 'mediaYoutubeLogoUnselected');?>" src="<?php echo $service['path'].$tempPath['image'];?>/spacer.gif" border="0" /></div>
		</div>
	</div>
	<div class="mediaSearchFormFrame">
		<iframe id="mediaSearchFrame" scrolling="no" frameborder="no" src="<?php echo $blogURL?>/plugin/<?php echo ($phpVersion < 4.2 ? 'YoutubeSearchView' : 'FlickrSearchView');?>/" style="border:medium none; overflow:hidden; width:100%;height:100%;"></iframe>
	</div>
	<?php
	$html = ob_get_contents();
	ob_end_clean();
	echo $html;
}

function getFlickrSearchView($target){
	global $blog, $pluginURL, $blogURL, $serviceURL, $service, $adminSkinSetting, $configVal, $__ts;
	requireModel('reader.common');
	requireComponent('Textcube.Model.Paging');
	requireComponent('Eolin.PHP.HTTPRequest');
	requireComponent('Textcube.Function.misc');
	if(!class_exists('pluginLang')) require_once ('lang/pluginLocal.php');
	if (!isset($blog['blogLanguage'])) {
		$blog['blogLanguage'] = $service['language'];
	}
	// Locale language file support.
	switch($blog['blogLanguage']) {
		case "zh-TW":
		case "zh-CN":
		case "en":
			$imgLang = '.'.$blog['blogLanguage'];
		break;
		default:
			$imgLang = '';
	}
	require_once "lib/phpFlickr.php";
	$data = misc::fetchConfigVal($configVal);
	$data['flickr_api_key'] = "f0b0e34cf04a234fb3bae61890f298cc"; //It's key for plugin. It does not change.	
	$data['myFlickrAuthType'] = isset($data['myFlickrAuthType']) ? $data['myFlickrAuthType'] : "email";
	$data['myFlickrAuthString'] = isset($data['myFlickrAuthString']) ? $data['myFlickrAuthString'] : "";
	$data['linkTarget'] = isset($data['linkTarget']) ? $data['linkTarget'] : "blank";
	$data['perpage']	= isset($data['perpage']) ? $data['perpage'] : 12; 

	$tempPath = getTempPath();
	ob_start();
	?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Searching for Flickr photos by keyword</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/basic.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/post.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/editor.css" />
	<!--[if lte IE 6]>
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/basic.ie.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/post.ie.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/editor.ie.css" />
	<![endif]-->
	<!--[if IE 7]>
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/basic.ie7.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/post.ie7.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/editor.ie7.css" />
	<![endif]-->
	<script type="text/javascript">
		//<![CDATA[
			var servicePath = "<?php echo $service['path'];?>";
			var blogURL = "<?php echo $blogURL;?>";
			var adminSkin = "<?php echo $adminSkinSetting['skin'];?>";
			var i18n = '<?php echo $blog['blogLanguage'];?>';
		//]]>
	</script>
	<script type="text/javascript" src="<?php echo $service['path'].$tempPath['script'];?>/byTextcube.js"></script>
	<script type="text/javascript" src="<?php echo $service['path'].$tempPath['script'];?>/EAF4.js"></script>
	<script type="text/javascript" src="<?php echo $service['path'].$tempPath['script'];?>/common2.js"></script>
	<script type="text/javascript" src="<?php echo $pluginURL;?>/script/default.js"></script>
	<link type="text/css" rel="stylesheet" href="<?php echo $pluginURL;?>/style/default.css" />	
</head>
<body>
<div id="loadingBar"><img src="<?php echo $pluginURL?>/images/loadingBar<?php echo $imgLang;?>.gif" border="0" alt="" /></div>
<div id="loadingSelect"><select class="selectUser"><option value="">&nbsp;loading ...</option></select></div>
<?php

	$personId = isset($_GET['person']) ? $_GET['person'] : "";
	$userSets = isset($_GET['userSets']) ? $_GET['userSets'] : "";

	if (isset($_GET['keyword']) || !empty($_GET['keyword'])) {
		$keyword = $_GET['keyword'];
		$keyword = ereg_replace('[[:space:]]+', ' ', trim($keyword));
	}else{
		$keyword = "";
	}

	if (!isset($_GET['userSets']) || empty($_GET['userSets'])) {
		$userSetsKey = "";
		$userSets = "";
	}else{
		$userSetsKey = "&userSets=".$_GET['userSets'];
		$userSets = htmlentities($_GET['userSets']);
	}

	if (!isset($_GET['orderby']) || empty($_GET['orderby']) || $_GET['orderby'] == 'none') {
		$orderbyKey = "none";
		$orderby = "";
	} else {
		$orderbyKey = $_GET['orderby'];
		$orderby =  htmlentities($_GET['orderby']);
	}
  
	if (!isset($_GET['page']) || $_GET['page'] <= 0) {
		$page = 1;
	} else {        
		$page = htmlentities($_GET['page']);
	}

	$f = new phpFlickr($data['flickr_api_key']);

	switch ($data['myFlickrAuthType']) {
		case 'email':
			$person = $f->people_findByEmail($data['myFlickrAuthString']);
			break;
		case 'name':
			$person = $f->people_findByUsername($data['myFlickrAuthString']);
			break;
		case 'nsid':
			$person = array('id' => $data['myFlickrAuthString']);
			break;
	}
	$userSetsList = "";
	if(!empty($person)){
		$photoSets = $f->photosets_getList((empty($personId) ? $person['id'] : $personId));
		if(count((array)$photoSets['photoset']) > 0){
			$userSetsList  = '<select id="userSets" name="userSets" class="selectUser" onchange="userSetsSelect(this);" ' . ($personId=="all" ? " disabled " : "") . '>';
			$userSetsList .= '<option value="">&bull; user sets</option>';
			foreach((array)$photoSets['photoset'] as $set) {
				$userSetsList .= '<option style="color:#777777;" value="' . $set['id'] .'" ' . ($userSets==$set['id'] ? " selected " : "") . '>&nbsp;&middot;' . $set['title'] . '</option>';
			}
			$userSetsList .= '</select>';
		}
		$contactsOption = "";
		$contacts = $f->contacts_getPublicList($person['id']);
		if(count((array)$contacts['contact']) > 0){
			$sort_array = array();
			foreach($contacts['contact'] AS $uniqid => $item){
				foreach($item AS $key=>$value){
					$sort_array[$key][$uniqid] = $value;
				}
			}
			array_multisort($sort_array['username'], SORT_ASC, $contacts['contact']);
			$contactsOption = '<option value="">&bull; friends</option>'.CRLF;
			foreach((array)$contacts['contact'] as $contact) {
				$contactsOption .= '<option style="color:#777777;" value="' . $contact['nsid'] . '"' . ($personId==$contact['nsid'] ? " selected ":"") . '>&nbsp;&middot;' . $contact['username'] . '</option>'.CRLF;
			}
		}
	}
	$myFlickrOption = (!empty($person) ? '<option value="' . $person['id'] . '" ' . ($person['id'] == $personId ? " selected " : "") . '>&bull; my flickr</option>' : '').CRLF;
	$userSetsDisbled = ((strlen($personId) > 3 && !empty($userSets))?" disabled " :"");
?>
<div id="flickrSearchBox">
	<div id="searchContent">
		<div class="searchForm">
			<form method="get" action="<?php echo $blogURL . '/plugin/FlickrSearchView/'; ?>">
				<div>
					<select name="person" id="person" class="selectUser" style="width:80px;" onchange="userSetsCheck(this);">
						<?php echo $myFlickrOption;?>
						<?php echo $contactsOption;?>
						<option value="all" <?php echo ($personId=="all" ? " selected " : "");?>>&bull; all flickr</option>
					</select><span id="userSetsList"><?php 
						echo $userSetsList;
					 ?></span><input type="radio" class="searchRadio" name="orderby" id="orderbyNone" value="none" <?php echo $userSetsDisbled;?> <?php echo ($orderbyKey=="none"?" checked ":"")?> /><label for="orderbyNone"><?php echo pluginLang::plts('미정렬');?></label><input
					 type="radio" class="searchRadio" name="orderby" id="orderbyPublished" value="date-posted-desc" <?php echo $userSetsDisbled;?> <?php echo ($orderbyKey=="date-posted-desc"?" checked ":"")?> /><label for="orderbyPublished"><?php echo pluginLang::plts('날짜');?></label><input
					 type="radio" class="searchRadio" name="orderby" id="orderbyInterestingness" value="interestingness-desc" <?php echo $userSetsDisbled;?> <?php echo ($orderbyKey=="interestingness-desc"?" checked ":"")?> /><label for="orderbyInterestingness"><?php echo pluginLang::plts('인기');?></label>
				</div>
				<div class="searchField">
					<input type="text" class="input-text keywordField" name="keyword" id="search-keyword" value="<?php echo (empty($keyword)?"":urldecode($keyword))?>" <?php echo $userSetsDisbled;?> />
					<input type="submit" value="<?php echo pluginLang::plts('검색');?>" class="input-button" onclick="searchStart();" /> 
				</div>
			</form>

<?php
		$pageLink = "?orderby={$orderbyKey}&person={$personId}{$userSetsKey}&keyword=" . rawurlencode($keyword);
		if (strlen($personId) > 3 || $personId == "all"){
			$searchUser = ((strlen($personId) > 3) ? array("user_id"=>$personId) : "" );
			if(strlen($personId) > 3 && !empty($userSets)) {
				$photos = $f->photosets_getPhotos($userSets, "owner_name", NULL, $data['perpage'], $page);
			} else{
				$searchArray = array($searchUser,"tags"=>$keyword, "text"=>$keyword, "sort"=>$orderby, "extras"=>"views,owner_name,date_upload,date_taken,license", "per_page"=>$data['perpage'], "page"=>$page);
				$photos = $f->photos_search($searchArray);	
			}

			$licenses = $f->photos_licenses_getInfo();
			if(count($licenses) > 0) {
				$sort_array = array();
				foreach($licenses AS $uniqid => $item){
					foreach($item AS $key=>$value){
						$sort_array[$key][$uniqid] = $value;
					}
				}
				array_multisort($sort_array['id'], SORT_ASC, $licenses);
			}
			
			if (count((array)$photos['photo']) > 0) {
				$target .= '<ul id="mediaSearchListId" class="mediaSearchList">'.CRLF;
				foreach ((array)$photos['photo'] as $photo) {
					if(!empty($userSets)){
						$photo['owner'] = $photos['owner'];
					}
					$imagePermalink = "http://www.flickr.com/photos/{$photo['owner']}/{$photo['id']}";
					$photoInfo = $f->photos_getInfo($photo['id']);
					$photoSizes = $f->photos_getSizes($photo['id']);
					$pathSizes = array('Large', 'Original');
					$thumbnailImage = array();
					$previewImage = array();
					$photoSizeHidden = "";
					$photoSizeList = '<select class="selectSize" name="photoSize" id="photoSize">'.CRLF;
					foreach ((array)$photoSizes as $photosize) {
						if($photosize['label'] == "Square"){
							$thumbnailImage['width'] = $photosize['width'];
							$thumbnailImage['height'] = $photosize['height'];
							$thumbnailImage['source'] = $photosize['source'];
						}
						if($photosize['label'] == "Small"){//Medium
							$previewImage['width'] = $photosize['width'];
							$previewImage['height'] = $photosize['height'];
							$previewImage['source'] = $photosize['source'];
						}
						if(!in_array($photosize['label'], $pathSizes)){
							$photoSizeList .= '		<option value="' . $photosize['label'] . '"' . ($photosize['label']=="Medium" ? " selected " : "") . '>&nbsp;' . $photosize['label'] . ' (size:' . $photosize['width'] ."x" . $photosize['height'] . ')</option>'.CRLF;	
						}
						if(!in_array($photosize['label'], $pathSizes)){
							$photoSizeHidden .= '<input type="hidden" name="' . $photosize['label'] . '" id="' . $photosize['label'] . '_' . $photo['id'] . '" value="' . $photosize['source'] . '" />'.CRLF; 
						}
					}
					$photoSizeList .= '</select>'.CRLF;

					$cclImagesPath = $pluginURL . "/images/ccl/";
					$cclIcons = array();
					$cclIcons[0] = '<img src="'.$cclImagesPath.'cc_icon_all_rights_small.gif" alt="all rights" class="cclIcons" border="0" />';
					$cclIcons[1] = '<img src="'.$cclImagesPath.'cc_icon_attribution_small.gif" alt="attribution" class="cclIcons" border="0" />';
					$cclIcons[2] = '<img src="'.$cclImagesPath.'cc_icon_noderivs_small.gif" alt="noderivs" class="cclIcons" border="0" />';
					$cclIcons[3] = '<img src="'.$cclImagesPath.'cc_icon_noncomm_small.gif" alt="noncomm" class="cclIcons" border="0" />';
					$cclIcons[4] = '<img src="'.$cclImagesPath.'cc_icon_sharealike_small.gif" alt="sharealike" class="cclIcons" border="0" />';

					$cclText = '<span class="cclText"> Some rights reserved</span>';
					switch ($photo['license']) {
						case 0: 
							$cclImages = $cclIcons[0]; 
							$cclText = '<span class="cclText"> All rights reserved</span>';
							break;
						case 1: 
							$cclImages = $cclIcons[1].$cclIcons[3].$cclIcons[4]; break;
						case 2: 
							$cclImages = $cclIcons[1].$cclIcons[3]; break;
						case 3: 
							$cclImages = $cclIcons[1].$cclIcons[3].$cclIcons[2]; break;
						case 4: 
							$cclImages = $cclIcons[1]; break;
						case 5: 
							$cclImages = $cclIcons[1].$cclIcons[4]; break;
						case 6: 
							$cclImages = $cclIcons[1].$cclIcons[2]; break;
						default:
							$cclImages = $cclIcons[0]; break;
					}

					$cclTitle = $licenses[$photo['license']]['name'];
					$cclLink = $licenses[$photo['license']]['url'];
					if (!empty($cclLink)) {
						$cclImageLink = '<a href="'.$cclLink.'" title="'.$cclTitle.'" target="_blank">'.$cclImages.$cclText.'</a>';
					} else {
						$cclImageLink = '<span title="'.$cclTitle.'">'.$cclImages.$cclText.'</span>';
					}

					$target .= '<li onclick="selectedThumbnail(this, \''.$photo['id'].'\', \'flickr\', \''.$photo['owner'].'\');" class="imgThumbnail" title="' . htmlspecialchars($photo['title']) . '"><img src="'.$thumbnailImage['source'].'" alt="' . htmlspecialchars($photo['title']) . '" />'.CRLF;
					$target .= '<div id="previewContent-'.$photo['id'].'" style="display:none">'.CRLF;
					$target .= '	<div class="mediaBox">'.CRLF;
					$target .= '		<input type="hidden" name="photoId" value="'.$photo['id'].'" />'.CRLF;
					$target .=			$photoSizeHidden;
					$target .= '		<div class="previewMedia">'.CRLF;
					$target .= '			<div class="previewImage" style="background:url('.$previewImage['source'].') center center no-repeat #ffffff;"><img src="'.$serviceURL.$tempPath['image'].'/spacer.gif" alt="' . htmlspecialchars($photo['title']) . '" /></div>'.CRLF;
					$target .= '		</div>'.CRLF;
					$target .= '		<div class="mediaInfo">'.CRLF;
					$target .= '			<div class="mediaTitle">'.CRLF;
					$target .= '				<h4 class="title" title="'.htmlspecialchars($photo['title']).'">'.UTF8::lessenAsEm(htmlspecialchars($photo['title']),30).'</h4>'.CRLF;
					$target .= '			</div>'.CRLF;
					$target .= '			<dl class="mediaName">'.CRLF;
					$target .= '				<dt>'.pluginLang::plts('등록자').'</dt> <dd>&nbsp;:&nbsp;'.htmlspecialchars($photo['ownername']).'</dd>'.CRLF;
					$target .= '			</dl>'.CRLF;
					$target .= '			<dl class="mediaDate">'.CRLF;
					$target .= '				<dt>'.pluginLang::plts('등록일시').'</dt> <dd>&nbsp;:&nbsp;'.Timestamp::formatDate(htmlspecialchars($photoInfo['dates']['posted'])).'</dd>'.CRLF;
					$target .= '			</dl>'.CRLF;
					$target .= '			<dl class="mediaSize">'.CRLF;
					$target .= '				<dt>'.pluginLang::plts('크기선택').'</dt> <dd>&nbsp;:&nbsp;'.$photoSizeList.'</dd>'.CRLF;
					$target .= '			</dl>'.CRLF;
					$target .= '			<dl class="mediaViewCount">'.CRLF;
					$target .= '				<dt>'.pluginLang::plts('조회수').'</dt> <dd>&nbsp;:&nbsp;'.number_format($photo['views']).'</dd>'.CRLF;
					$target .= '			</dl>'.CRLF;
					$target .= '			<dl class="mediaLicense">'.CRLF;
					$target .= '				<dt>'.pluginLang::plts('라이센스').'</dt> <dd class="mediaLicenseIcons">&nbsp;:&nbsp;'.$cclImageLink.'</dd>'.CRLF;
					$target .= '			</dl>'.CRLF;
					$target .= '		</div>'.CRLF;
					$target .= '	</div>'.CRLF;
					$target .= '</div>'.CRLF;	
				}	
				$target .= '</ul>'.CRLF;
				$target .= '<div class="paging-list">'.CRLF;
				$photos['total'] = $photos['total'] > 996 ? 996 : $photos['total'];

				$paging = getFetchWithPaging($photos['total'], $page, $data['perpage'], "$blogURL/plugin/FlickrSearchView/", $pageLink . "&page=");
				$pagingTemplate = '[##_paging_rep_##]';
				$pagingItemTemplate = '<a [##_paging_rep_link_##] class="num" onclick="if(this.href){return searchStart();}">[##_paging_rep_link_num_##]</a>';
				
				$prev_page = isset($paging['prev']) ? " href='{$pageLink}&page={$paging['prev']}' onclick='searchStart();' " : '';
				$next_page = isset($paging['next']) ? " href='{$pageLink}&page={$paging['next']}' onclick='searchStart();' " : '';
				$no_more_prev = isset($paging['prev']) ? '' : 'no-more-prev';
				$no_more_next = isset($paging['next']) ? '' : 'no-more-next';

				$target .= '<a '.$prev_page.' style="background:url('.$pluginURL.'/images/bull_page_prev.gif) left 1px no-repeat;" class="prev '.$no_more_prev.'">'.pluginLang::plts('이전').' </a>'.CRLF;
				$target .= '<span class="numbox">'.str_repeat("\t", 12).Paging::getPagingView($paging, $pagingTemplate, $pagingItemTemplate).'</span>'.CRLF;
				$target .= '<a '.$next_page.' style="background:url('.$pluginURL.'/images/bull_page_next.gif) right 1px no-repeat;" class="next '.$no_more_next.'">'.pluginLang::plts('다음').'</a>'.CRLF;
				$target .= '<div class="totalResults">'.CRLF;
				$target .= pluginLang::plfs('총 %1 건',$photos['total']);
				$target .= '</div>'.CRLF;
				$target .= '</div>'.CRLF;

			} else {
				$target .= '<div id="searchErrorMsg" class="noMediaList">' . pluginLang::plts('검색된 사진이 없습니다.') . '</div>';
			}
		} else {
			$target .= '<div id="searchErrorMsg" class="noMediaList">' . pluginLang::plts('검색된 사진이 없습니다.') . '</div>';
		}
		unset($feed);
		unset($xmls);
		echo $target;
?>
		</div>
	</div>
	<style type="text/css">
		.mediaBox .previewMedia{
			background:url(<?php echo $pluginURL?>/images/photoPreview.png) center top no-repeat #fff;
		}
	</style>
	<div id="previewContent">
	<form name="previewForm">
		<div id="previewMediaInfo">
			<div class="mediaBox">
				<div class="previewMedia">&nbsp;</div>
				<div class="mediaInfo">
					<div class="mediaTitle">
						<h4 class="title"><?php echo pluginLang::plts('사진을 선택하세요.');?></h4>
					</div>
					<dl class="mediaName">
						<dt><?php echo pluginLang::plts('등록자');?></dt> <dd id="iMediaName">&nbsp;:&nbsp;</dd>
					</dl>
					<dl class="mediaDate">
						<dt><?php echo pluginLang::plts('등록일시');?></dt> <dd id="iMediaDate">&nbsp;:&nbsp;</dd>
					</dl>
					<dl class="mediaSize">
						<dt><?php echo pluginLang::plts('크기선택');?></dt> <dd id="iMediaSize">&nbsp;:&nbsp;</dd>
					</dl>
					<dl class="mediaViewCount">
						<dt><?php echo pluginLang::plts('조회수');?></dt> <dd id="iMediaViewCount">&nbsp;:&nbsp;</dd>
					</dl>
					<dl class="mediaLicense">
						<dt><?php echo pluginLang::plts('라이센스');?></dt> <dd>&nbsp;:&nbsp;</dd>
					</dl>
				</div>
			</div>
		</div>
		<div class="mediaAlignBox">
			<div class="mediaAlignList">
				<input type="radio" name="insertAlign" id="mediaAlignLeft" value="left" class="alignRadio" /><label for="mediaAlignLeft"><img src="<?php echo $pluginURL;?>/images/alignLeftIcon.gif" border="0" /><?php echo pluginLang::plts('왼쪽');?></label>
				<input type="radio" name="insertAlign" id="mediaAlignCenter" value="center" class="alignRadio" checked /><label for="mediaAlignCenter"><img src="<?php echo $pluginURL;?>/images/alignCenterIcon.gif" border="0" /><?php echo pluginLang::plts('가운데');?></label>
				<input type="radio" name="insertAlign" id="mediaAlignRight" value="right" class="alignRadio" /><label for="mediaAlignRight"><img src="<?php echo $pluginURL;?>/images/alignRightIcon.gif" border="0" /><?php echo pluginLang::plts('오른쪽');?></label>
			</div>
		</div>
		<div class="mediaAction">
			<div class="buttonArea">
				<input type="button" class="input-button" value="<?php echo pluginLang::plts('확인');?>" onclick="mediaInsert('flickr');" /> 
				<input type="button" class="input-button" value="<?php echo pluginLang::plts('취소');?>" onclick="cancel();" /> 
			</div>
		</div>
		<input type="hidden" name="linkTarget" value="<?php echo $data['linkTarget'];?>" />
	</form>
	</div>
</div>
<script language="JavaScript" type="text/javascript">
	function loadingBarClear() {
		document.getElementById('loadingBar').style.display = "none";
	}
	if(window.attachEvent) window.attachEvent('onload',loadingBarClear);
	else window.addEventListener('load',loadingBarClear,false);
</script>
</body>
</html>
<?php
	$html = ob_get_contents();
	ob_end_clean();
	echo $html;
	flush();
}

function getFlickrUserSetsView($target) {
	global $pluginURL, $blogURL, $serviceURL, $service, $adminSkinSetting, $configVal;
	requireModel('reader.common');
	requireComponent('Textcube.Model.Paging');
	requireComponent('Eolin.PHP.HTTPRequest');
	requireComponent('Textcube.Function.misc');

	require_once "lib/phpFlickr.php";
	$data = misc::fetchConfigVal($configVal);
	$data['flickr_api_key'] = "f0b0e34cf04a234fb3bae61890f298cc"; //It's key for plugin. It does not change.	

	$f = new phpFlickr($data['flickr_api_key']);
	$userSetsList = "";
	$personId = isset($_GET['person']) ? $_GET['person'] : "";
	if(!empty($personId) && strlen($personId) > 3){
		$photoSets = $f->photosets_getList($personId);
		if(count((array)$photoSets['photoset']) > 0){
			$userSetsList  = '<select id="userSets" name="userSets" class="selectUser" onchange="userSetsSelect(this);">';
			$userSetsList .= '<option value="">&bull; user sets</option>';
			foreach((array)$photoSets['photoset'] as $set) {
				$userSetsList .= '<option style="color:#777777;" value="' . $set['id'] .'">&nbsp;&middot;' . $set['title'] . '</option>';
			}
			$userSetsList .= '</select>';
		}
	}
	echo $userSetsList;
}

function getYoutubeSearchView($target){
	global $pluginURL, $blogURL, $serviceURL, $service, $adminSkinSetting, $configVal, $__ts;
	requireModel('reader.common');
	requireComponent('Textcube.Model.Paging');
	requireComponent('Eolin.PHP.HTTPRequest');
	requireComponent('Textcube.Function.misc');

	$data = misc::fetchConfigVal($configVal);
	$data['ytUsername']		= isset($data['ytUsername']) ? $data['ytUsername'] : ""; 
	$data['ytMaxResults']	= isset($data['ytMaxResults']) ? $data['ytMaxResults'] : 16; 
	if(!class_exists('pluginLang')) require_once ('lang/pluginLocal.php');
	if (!isset($blog['blogLanguage'])) {
		$blog['blogLanguage'] = $service['language'];
	}
	switch($blog['blogLanguage']) {
		case "zh-TW":
		case "zh-CN":
		case "en":
			$imgLang = '.'.$blog['blogLanguage'];
		break;
		default:
			$imgLang = '';
	}
	$tempPath = getTempPath();
	ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Searching for YouTube videos by keyword</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/basic.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/post.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/editor.css" />
	<!--[if lte IE 6]>
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/basic.ie.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/post.ie.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/editor.ie.css" />
	<![endif]-->
	<!--[if IE 7]>
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/basic.ie7.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/post.ie7.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="<?php echo $service['path'].$adminSkinSetting['skin'];?>/editor.ie7.css" />
	<![endif]-->
	<script type="text/javascript">
		//<![CDATA[
			var servicePath = "<?php echo $service['path'];?>";
			var blogURL = "<?php echo $blogURL;?>";
			var adminSkin = "<?php echo $adminSkinSetting['skin'];?>";
			var i18n = '<?php echo $blog['blogLanguage'];?>';
		//]]>
	</script>

	<script type="text/javascript" src="<?php echo $pluginURL;?>/script/default.js"></script>
	<link type="text/css" rel="stylesheet" href="<?php echo $pluginURL;?>/style/default.css" />	
</head>
<body>
<div id="loadingBar"><img src="<?php echo $pluginURL?>/images/loadingBar<?php echo $imgLang;?>.gif" border="0" alt="" /></div>
<?php
	if (isset($_GET['keyword']) || !empty($_GET['keyword'])) {
		$keyword = $_GET['keyword'];
		$keyword = ereg_replace('[[:space:]]+', ' ', trim($keyword));
		$keyword = rawurlencode($keyword);
	}else{
		$keyword = "";
	}

	if (isset($_GET['myYoutube']) || !empty($_GET['myYoutube'])) {
		$myYoutube = "&myYoutube=".$_GET['myYoutube'];
	}else{
		$myYoutube = "";
	}

	if (!isset($_GET['orderby']) || empty($_GET['orderby']) || $_GET['orderby'] == 'none') {
		$orderbyKey = "none";
		$orderby = "";
	} else {
		$orderbyKey = $_GET['orderby'];
		$orderby = '&orderby=' . htmlentities($_GET['orderby']);
	}
  
	if (!isset($_GET['page']) || $_GET['page'] <= 0) {
		$startIndex = 1;
		$page = 1;
	} else {        
		$page = htmlentities($_GET['page']);
		$startIndex = (($page-1) * $data['ytMaxResults'])+1;  
	}
	
	$myYoutubeDisabled = empty($data['ytUsername']) ? ' disabled ' : '';

	if(!empty($data['ytUsername'])){
		$youtubeUserlist .= '<option style="color:#0066FF;" value="' . $data['ytUsername'] . '" ' . ($_GET['myYoutube']==$data['ytUsername'] ? " selected ":"") . '>&nbsp;&middot;' . $data['ytUsername'] . '</option>'.CRLF;
		$feedURL = "http://gdata.youtube.com/feeds/api/users/" . $data['ytUsername'] . "/subscriptions";
		list($result, $feed, $xml) = getMediaViewXMLResource($feedURL);  
		if ($result == 0) {
			$xmls = new XMLStruct();
			$tubeUserList = array();
			$totalResults = "";
			if ($xmls->open($xml, $service['encoding'])) {
				if ($xmls->getAttribute('/feed', 'xmlns:openSearch')) {
					$totalResults = $xmls->getValue("/feed/openSearch:totalResults");
					$item = array();
					for ($i = 0; $link = $xmls->getValue("/feed/entry[$i]/id"); $i++) {
						$item['permalink'] = rawurldecode($link);
						$item['username'] = $xmls->getValue("/feed/entry[$i]/yt:username");
						array_push($tubeUserList , $item);
					}
				}
			}	
			if (count($tubeUserList ) > 0) {
				$youtubeUserlist .= '<option value="">&bull; friends</option>'.CRLF;
				foreach($tubeUserList  as $item) {
					$youtubeUserlist .= '<option style="color:#777777;" value="' . $item['username'] . '"' . ($_GET['myYoutube']==$item['username'] ? " selected ":"") . '>&nbsp;&middot;' . $item['username'] . '</option>'.CRLF;
				}
			}
			unset($tubeUserList);
		}
	}
?>
<div id="youtubeSearchBox">
	<div id="searchContent">
		<div class="searchForm">
			<form method="get" action="<?php echo $blogURL . '/plugin/YoutubeSearchView/'; ?>">
				<div>
					<select name="myYoutube" id="myYoutube" class="selectUser" onchange="selectUserCheck(this);" <?php echo $myYoutubeDisabled;?> >
						<option value="">&bull; select user</option>
						<?php echo $youtubeUserlist;?>
					</select><input 
					 type="radio" class="searchRadio" name="orderby" id="orderbyNone" value="none" <?php echo ($orderbyKey=="none"? " checked ":"")?> /><label for="orderbyNone"><?php echo pluginLang::plts('미정렬');?></label><input
					 type="radio" class="searchRadio" name="orderby" id="orderbyPublished" value="published" <?php echo ($orderbyKey=="published"? " checked ":"")?> /><label for="orderbyPublished"><?php echo pluginLang::plts('날짜');?></label><input
					 type="radio" class="searchRadio" name="orderby" id="orderbyViewCount" value="viewCount" <?php echo ($orderbyKey=="viewCount"? " checked ":"")?> /><label for="orderbyViewCount"><?php echo pluginLang::plts('조회');?></label><input
					 type="radio" class="searchRadio" name="orderby" id="orderbyRating" value="rating" <?php echo ($orderbyKey=="rating"? " checked ":"")?> /><label for="orderbyRating"><?php echo pluginLang::plts('추천');?></label>&nbsp;
				</div>
				<div class="searchField">
					<input type="text" class="input-text keywordField" name="keyword" id="search-keyword" value="<?php echo (empty($keyword)?"":urldecode($keyword))?>" />
					<input type="submit" value="<?php echo pluginLang::plts('검색');?>" class="input-button" onclick="searchStart();" /> 
				</div>
			</form>

<?php
	  
		$pageLink = "?orderby={$orderbyKey}{$myYoutube}&keyword={$keyword}";
		if (!isset($_GET['myYoutube']) || empty($_GET['myYoutube'])) {
			$feedURL = "http://gdata.youtube.com/feeds/api/videos?vq={$keyword}&max-results={$data['ytMaxResults']}&start-index={$startIndex}" . $orderby;
		}else{
			if (!empty($_GET['keyword'])) {
				$keyword = "vq={$keyword}&";
			}else{
				$keyword = "";
			}
			$feedURL = "http://gdata.youtube.com/feeds/api/users/" . $_GET['myYoutube'] . "/uploads?{$keyword}max-results={$data['ytMaxResults']}&start-index={$startIndex}" . $orderby;
		}

		$thumbnailIndex = 2; //썸네일 사진 인텍스 번호 [2,1,3 : width=130 : height=97 / 0 : width=320 : height=240]
		list($result, $feed, $xml) = getMediaViewXMLResource($feedURL);  
		if ($result == 0) {
			$xmls = new XMLStruct();
			$tubeEntries = array();
			if ($xmls->open($xml, $service['encoding'])) {
				if ($xmls->getAttribute('/feed', 'xmlns:openSearch')) {
					$item = array();
					$item['totalResults'] = $xmls->getValue("/feed/openSearch:totalResults");
					$item['startIndex'] = $xmls->getValue("/feed/openSearch:startIndex");
					$item['itemsPerPage'] = $xmls->getValue("/feed/openSearch:itemsPerPage");
					for ($i = 0; $link = $xmls->getValue("/feed/entry[$i]/id"); $i++) {
						$item['permalink'] = rawurldecode($link);
						$item['author'] = $xmls->getValue("/feed/entry[$i]/author/name");
						$item['title'] = $xmls->getValue("/feed/entry[$i]/media:group/media:title");
						$item['mediaURL'] = $xmls->getAttribute("/feed/entry[$i]/media:group/media:player", 'url');
						$item['mediaId'] = substr($item['mediaURL'], strrpos($item['mediaURL'], "=") + 1);
						$item['mediaLink'] = "http://youtube.com/v/" . $item['mediaId'];
						$item['mediaThumbnailLink'] = "http://img.youtube.com/vi/" . $item['mediaId'] . "/{$thumbnailIndex}.jpg";
						$item['duration'] = $xmls->getAttribute("/feed/entry[$i]/media:group/yt:duration", 'seconds'); //재생시간
						$item['viewCount'] = $xmls->getAttribute("/feed/entry[$i]/yt:statistics", 'viewCount'); //조회수
						$item['published'] = parseDate($xmls->getValue("/feed/entry[$i]/published"));
						array_push($tubeEntries, $item);
					}
				}
			}	
			if (count($tubeEntries) > 0) {
				$target .= '<ul id="mediaSearchListId" class="mediaSearchList">'.CRLF;
				$i = 0;
				foreach($tubeEntries as $item) {
					$target .= '<li onclick="selectedThumbnail(this, \''.$item['mediaId'].'\', \'youtube\', \'\');" class="imgThumbnail" style="background:url('.$item['mediaThumbnailLink'].') center center no-repeat #ffffff;" title="' . htmlspecialchars($item['title']) . '"><img src="'.$serviceURL.$tempPath['image'].'/spacer.gif" alt="' . htmlspecialchars($item['title']) . '" />'.CRLF;
					$target .= '<div id="previewContent-'.$item['mediaId'].'" style="display:none">'.CRLF;
					$target .= '	<div class="mediaBox">'.CRLF;
					$target .= '		<div class="previewMedia">'.CRLF;
					$target .= '			<object width="100%" height="100%"><param name="movie" value="http://www.youtube.com/v/'.$item['mediaId'].'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'.$item['mediaId'].'" type="application/x-shockwave-flash" wmode="transparent" width="100%" height="100%"></embed></object>'.CRLF;
					$target .= '		</div>'.CRLF;
					$target .= '		<div class="mediaInfo">'.CRLF;
					$target .= '			<div class="mediaTitle">'.CRLF;
					$target .= '				<h4 class="title" title="'.htmlspecialchars($item['title']).'">'.UTF8::lessenAsEm(htmlspecialchars($item['title']),30).'</h4>'.CRLF;
					$target .= '			</div>'.CRLF;
					$target .= '			<dl class="mediaName">'.CRLF;
					$target .= '				<dt>'.pluginLang::plts('등록자').'</dt> <dd>&nbsp;:&nbsp;'.htmlspecialchars($item['author']).'</dd>'.CRLF;
					$target .= '			</dl>'.CRLF;
					$target .= '			<dl class="mediaDate">'.CRLF;
					$target .= '				<dt>'.pluginLang::plts('등록일시').'</dt> <dd>&nbsp;:&nbsp;'.Timestamp::formatDate(htmlspecialchars($item['published'])).'</dd>'.CRLF;
					$target .= '			</dl>'.CRLF;
					$target .= '			<dl class="mediaTime">'.CRLF;
					$target .= '				<dt>'.pluginLang::plts('영상길이').'</dt> <dd>&nbsp;:&nbsp;'.getMediaTimePeriod($item['duration']).'</dd>'.CRLF;
					$target .= '			</dl>'.CRLF;
					$target .= '			<dl class="mediaViewCount">'.CRLF;
					$target .= '				<dt>'.pluginLang::plts('조회수').'</dt> <dd>&nbsp;:&nbsp;'.number_format($item['viewCount']).'</dd>'.CRLF;
					$target .= '			</dl>'.CRLF;
					$target .= '		</div>'.CRLF;
					$target .= '	</div>'.CRLF;
					$target .= '</div>'.CRLF;		
					$target .= '</li>'.CRLF;
					$i++;
				}
				$target .= '</ul>'.CRLF;
				$target .= '<div class="paging-list">'.CRLF;
				$item['totalResults'] = $item['totalResults'] > 996 ? 996 : $item['totalResults'];

				$paging = getFetchWithPaging($item['totalResults'], $page, $item['itemsPerPage'], "$blogURL/plugin/YoutubeSearchView/", $pageLink . "&page=");
				$pagingTemplate = '[##_paging_rep_##]';
				$pagingItemTemplate = '<a [##_paging_rep_link_##] class="num" onclick="if(this.href){return searchStart();}">[##_paging_rep_link_num_##]</a>';
				
				$prev_page = isset($paging['prev']) ? " href='{$pageLink}&page={$paging['prev']}' onclick='searchStart();' " : '';
				$next_page = isset($paging['next']) ? " href='{$pageLink}&page={$paging['next']}' onclick='searchStart();' " : '';
				$no_more_prev = isset($paging['prev']) ? '' : 'no-more-prev';
				$no_more_next = isset($paging['next']) ? '' : 'no-more-next';

				$target .= '<a '.$prev_page.' style="background:url('.$pluginURL.'/images/bull_page_prev.gif) left 1px no-repeat;" class="prev '.$no_more_prev.'">'.pluginLang::plts('이전').' </a>'.CRLF;
				$target .= '<span class="numbox">'.str_repeat("\t", 12).Paging::getPagingView($paging, $pagingTemplate, $pagingItemTemplate).'</span>'.CRLF;
				$target .= '<a '.$next_page.' style="background:url('.$pluginURL.'/images/bull_page_next.gif) right 1px no-repeat;" class="next '.$no_more_next.'">'.pluginLang::plts('다음').'</a>'.CRLF;
				$target .= '<div class="totalResults">'.CRLF;
				$target .= pluginLang::plfs('총 %1 건',$item['totalResults']);
				$target .= '</div>'.CRLF;
				$target .= '</div>'.CRLF;
			} else {
				$target .= '<div id="searchErrorMsg" class="noMediaList">' . pluginLang::plts('검색된 동영상이 없습니다.') . '</div>';
			}
		} else {
			$target .= '<div id="searchErrorMsg" class="noMediaList">' . pluginLang::plts('검색된 동영상이 없습니다.') . '</div>';
		}

		unset($feed);
		unset($xmls);
		unset($tubeEntries);
		echo $target;

?>
		</div>
	</div>
	<style type="text/css">
		.mediaBox .previewMedia{
			background:url(<?php echo $pluginURL?>/images/mediaPreview.png) center top no-repeat #fff;
		}
	</style>
	<div id="previewContent">
	<form name="previewForm">
		<div id="previewMediaInfo">
			<div class="mediaBox">
				<div class="previewMedia">&nbsp;</div>
				<div class="mediaInfo">
					<div class="mediaTitle">
						<h4 class="title"><?php echo pluginLang::plts('동영상을 선택하세요.');?></h4>
					</div>
					<dl class="mediaName">
						<dt><?php echo pluginLang::plts('등록자');?></dt> <dd>&nbsp;:&nbsp;</dd>
					</dl>
					<dl class="mediaDate">
						<dt><?php echo pluginLang::plts('등록일시');?></dt> <dd>&nbsp;:&nbsp;</dd>
					</dl>
					<dl class="mediaTime">
						<dt><?php echo pluginLang::plts('영상길이');?></dt> <dd>&nbsp;:&nbsp;</dd>
					</dl>
					<dl class="mediaViewCount">
						<dt><?php echo pluginLang::plts('조회수');?></dt> <dd>&nbsp;:&nbsp;</dd>
					</dl>
				</div>
			</div>
		</div>
		<div class="mediaAlignBox">
			<div class="mediaAlignList">
				<input type="radio" name="insertAlign" id="mediaAlignLeft" value="left" class="alignRadio" /><label for="mediaAlignLeft"><img src="<?php echo $pluginURL;?>/images/alignLeftIcon.gif" border="0" /><?php echo pluginLang::plts('왼쪽');?></label>
				<input type="radio" name="insertAlign" id="mediaAlignCenter" value="center" class="alignRadio" checked /><label for="mediaAlignCenter"><img src="<?php echo $pluginURL;?>/images/alignCenterIcon.gif" border="0" /><?php echo pluginLang::plts('가운데');?></label>
				<input type="radio" name="insertAlign" id="mediaAlignRight" value="right" class="alignRadio" /><label for="mediaAlignRight"><img src="<?php echo $pluginURL;?>/images/alignRightIcon.gif" border="0" /><?php echo pluginLang::plts('오른쪽');?></label>
			</div>
		</div>
		<div class="mediaAction">
			<div class="buttonArea">
				<input type="button" class="input-button" value="<?php echo pluginLang::plts('확인');?>" onclick="mediaInsert('youtube');" /> 
				<input type="button" class="input-button" value="<?php echo pluginLang::plts('취소');?>" onclick="cancel();" />
			</div>
		</div>
	</form>
	</div>
</div>
<script language="JavaScript" type="text/javascript">
	function loadingBarClear() {
		document.getElementById('loadingBar').style.display = "none";
	}
	if(window.attachEvent) window.attachEvent('onload',loadingBarClear);
	else window.addEventListener('load',loadingBarClear,false);
</script>
</body>
</html>
<?php
	$html = ob_get_contents();
	ob_end_clean();
	echo $html;
}

 function getMediaTimePeriod($time) {
	global $__ts;
	if(!class_exists('pluginLang')) require_once ('lang/pluginLocal.php');
	
    $fixStr = array(pluginLang::plts('시간 '), pluginLang::plts('분 '), pluginLang::plts('초'));
    $fixStep = array(24, 60, 60);
    $putStr = "";

	$num = count($fixStr) -1;
    for($i = $num; $i > 0; $i --) {
        $tmp[$i] = $time % $fixStep[$i];
        $time = intval($time / $fixStep[$i]);
    }
    $tmp[0] = $time;

    $flag = false;
    for($i = 0; $i <= $num; $i ++) {
        if($tmp[$i] || $flag) {
            $putStr .= $tmp[$i].$fixStr[$i];
            $flag = ture;
        }
    }
    return ( $putStr ) ? $putStr : '0'.pluginLang::plts('초');
 }

function getFetchWithPaging($totalCount, $page, $count, $url = null, $prefix = '?page=', $countItem = null) {
	global $folderURL, $service;
	if ($url === null)
		$url = $folderURL;
	$paging = array('url' => $url, 'prefix' => $prefix, 'postfix' => '');
	$paging['total'] = $totalCount;
	if (empty($count)) $count = 1;
	$paging['pages'] = intval(ceil($paging['total'] / $count));
	$paging['page'] = is_numeric($page) ? $page : 1;
	if ($paging['page'] > $paging['pages']) {
		$paging['page'] = $paging['pages'];
		if ($paging['pages'] > 0)
			$paging['prev'] = $paging['pages'] - 1;
		//return array(array(), $paging);
	}
	if ($paging['page'] > 1)
		$paging['prev'] = $paging['page'] - 1;
	if ($paging['page'] < $paging['pages'])
		$paging['next'] = $paging['page'] + 1;
	$offset = ($paging['page'] - 1) * $count;
	if ($offset < 0) $offset = 0;
	if ($countItem !== null) $count = $countItem;
	return $paging;
}

function getMediaViewXMLResource($url=null) {
	global $service;
	$xml = fireEvent('GetRemoteFeed', null, $url);
	if (empty($xml)) {
		requireComponent('Eolin.PHP.HTTPRequest');
		$request = new HTTPRequest($url);
		$request->timeout = 3;
		if (!$request->send())
			return array(2, null, null);
		$xml = $request->responseText;
	}
	$feed = array('xmlURL' => $url);
	$xmls = new XMLStruct();
	if (!$xmls->open($xml, $service['encoding'])) {
		if(preg_match_all('/<link .*?rel\s*=\s*[\'"]?alternate.*?>/i', $xml, $matches)) {
			foreach($matches[0] as $link) {
				$attributes = getAttributesFromString($link);
				if(isset($attributes['href'])) {
					$urlInfo = parse_url($url);
					$rssInfo = parse_url($attributes['href']);
					$rssURL = false;
					if(isset($rssInfo['scheme']) && $rssInfo['scheme'] == 'http')
						$rssURL = $attributes['href'];
					else if(isset($rssInfo['path'])) {
						if($rssInfo['path']{0} == '/')
							$rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}{$rssInfo['path']}";							
						else
							$rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}".(isset($urlInfo['path']) ? rtrim($urlInfo['path'], '/') : '').'/'.$rssInfo['path'];
					}
					if($rssURL && $url != $rssURL)
						return getRemoteFeed($rssURL);
				}
			}
		}
		return array(3, null, null);
	}
	
	if ($xmls->getAttribute('/rss', 'version')) {
		$feed['blogURL'] = $xmls->getValue('/rss/channel/link');
		$feed['title'] = $xmls->getValue('/rss/channel/title');
		$feed['description'] = $xmls->getValue('/rss/channel/description');
		if (Validator::language($xmls->getValue('/rss/channel/language')))
			$feed['language'] = $xmls->getValue('/rss/channel/language');
		else if (Validator::language($xmls->getValue('/rss/channel/dc:language')))
			$feed['language'] = $xmls->getValue('/rss/channel/dc:language');
		else
			$feed['language'] = 'en-US';
		$feed['modified'] = gmmktime();
	} else if ($xmls->getAttribute('/feed', 'xmlns:openSearch')) {
		$feed['blogURL'] = $xmls->getAttribute('/feed/link', 'href');
		$feed['title'] = $xmls->getValue('/feed/title');
		$feed['description'] = $xmls->getValue('/feed/tagline');
		if(Validator::language($xmls->getAttribute('/feed', 'xml:lang')))
			$feed['language'] = $xmls->getAttribute('/feed', 'xml:lang');
		else
			$feed['language'] = 'en-US';
		$feed['modified'] = gmmktime();
	} else {
		return array(3, null, null);
	}

	$feed['blogURL'] = tc_escape_string(UTF8::lessenAsEncoding(UTF8::correct($feed['blogURL'])));
	$feed['title'] = tc_escape_string(UTF8::lessenAsEncoding(UTF8::correct($feed['title'])));
	$feed['description'] = tc_escape_string(UTF8::lessenAsEncoding(UTF8::correct(stripHTML($feed['description']))));

	return array(0, $feed, $xml);
}

function getTempPath() {
	list($currentTextcubeVersion) = explode(' ', TEXTCUBE_VERSION, 2);
	$scriptPath = ($currentTextcubeVersion >= 1.8) ? '/resources/script' : '/script';
	$imagesPath = ($currentTextcubeVersion >= 1.8) ? '/resources/image' : '/image';
	return array('script'=>$scriptPath, 'image'=>$imagesPath);
}

function getMediaSearchViewDataSet($DATA){
	requireComponent('Textcube.Function.misc');
	$cfg = misc::fetchConfigVal($DATA);
	$phpVersion = phpversion();
	if (!empty($cfg['myFlickrAuthType']) && !empty($cfg['myFlickrAuthString']) && $phpVersion >= 4.2) {
		require_once "lib/phpFlickr.php";
		$cfg['flickr_api_key'] = "f0b0e34cf04a234fb3bae61890f298cc"; //It's key for plugin. It does not change.	
		$f = new phpFlickr($cfg['flickr_api_key']);

		switch ($cfg['myFlickrAuthType']) {
			case 'email':
				if (!empty($cfg['myFlickrAuthString']) && !preg_match('/^[^@]+@([-a-zA-Z0-9]+\.)+[-a-zA-Z0-9]+$/', $cfg['myFlickrAuthString'])){
					 return "::INPUT FLICKR USER ERROR::\n\n  Invalid Flickr e-mail format. Please Try again.  ";
				} else {
					$person = $f->people_findByEmail($cfg['myFlickrAuthString']);
					if ($person['id'] == null) {
						return "::INPUT FLICKR USER ERROR::\n\n  No user with the supplied email address was found.  ";
					}
				}
				break;
			case 'name':
				if (!empty($cfg['myFlickrAuthString'])){
					$person = $f->people_findByUsername($cfg['myFlickrAuthString']);
					if ($person['id'] == null) {
						return "::INPUT FLICKR USER ERROR::\n\n  No user with the supplied username was found.  ";
					}
				}
				break;
			case 'nsid':
				if (!empty($cfg['myFlickrAuthString']) && !preg_match('/^\d+@N\d+$/', $cfg['myFlickrAuthString'])){
					 return "::INPUT FLICKR USER ERROR::\n\n  Invalid Flickr NSID format. Please Try again.  ";
				} else {
					$person = $f->people_getInfo($cfg['myFlickrAuthString']);
					if ($person['id'] == null) {
						return "::INPUT FLICKR USER ERROR::\n\n  No user with the supplied username was found.  ";
					}
				}
				break;
		}
	}

	if (!empty($cfg['ytUsername']) && !preg_match('/^[\w\d]+$/i', $cfg['ytUsername'])){
		 return "::INPUT YOUTUBE USER ERROR::\n\n  Invalid YouTube username format. Please Try again.  ";
	}
	return true;
}

function CFG_MediaSearchViewDataSet($plugin){
	global $database, $blogid, $configVal, $__ts;
	requireComponent('Textcube.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	$phpVersion = phpversion();
	if(!class_exists('pluginLang')) require_once ('lang/pluginLocal.php');
	$setupAlert = ($phpVersion < 4.2 ? pluginLang::plfs('<script type="text/javascript">alert(":: Flickr 플러그인 사용 안내 ::\n\n사용하고 계시는 PHP 버전이 \''.$phpVersion.'\'입니다. 플러그인에서 Flickr 데이터를 추출하기 위해 사용된 PEAR 패키지에서 PHP 4.2.0 이상에서만 사용할 수 있는 \'is_a()\' 클래스를 사용하였기 때문에 Flickr와의 데이터 연동에 제약이 따를 수 있습니다.  ");</script>') : '');

	$manifest = NULL;
	$manifest .= '<?xml version="1.0" encoding="utf-8"?>'.CRLF;
	$manifest .= '<config dataValHandler="getMediaSearchViewDataSet" >'.CRLF;
	$manifest .= '	<window width="520" height="440" />'.CRLF;
	$manifest .= '		<fieldset legend="Flickr user setting" >'.CRLF;
	$manifest .= '			<field title=": My Flickr authentication type" name="myFlickrAuthType" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '				<op value="email" checked="checked"><![CDATA[E-MAIL&nbsp;]]></op>'.CRLF;
	$manifest .= '				<op value="name"><![CDATA[USERNAME&nbsp;]]></op>'.CRLF;
	$manifest .= '				<op value="nsid">NSID</op>'.CRLF;
	$manifest .= '			</field>'.CRLF;
	$manifest .= '			<field title=": My Flickr authentication string" name="myFlickrAuthString" type="text" size="35" value="" titledirection="bk" >'.CRLF;
	$manifest .= '				<caption><![CDATA[ex) <b>e-mail : </b>gildong@ex.com, &nbsp;<b>username : </b>gildong, &nbsp;<b>nsid : </b>123456789@N01 ' . $setupAlert . ']]></caption>'.CRLF;
	$manifest .= '			</field>'.CRLF;
	$manifest .= '			<field title=": Image link target" name="linkTarget" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '				<op value="blank" checked="checked"><![CDATA[Blank&nbsp;]]></op>'.CRLF;
	$manifest .= '				<op value="self">Self</op>'.CRLF;
	$manifest .= '			</field>'.CRLF;
	$manifest .= '		</fieldset>'.CRLF;
	$manifest .= '		<fieldset legend="YouTube user setting" >'.CRLF;
	$manifest .= '			<field title=": My YouTube username" name="ytUsername" type="text" size="15" value="" titledirection="bk" >'.CRLF;
	$manifest .= '				<caption><![CDATA[ex) hongildong]]></caption>'.CRLF;
	$manifest .= '			</field>'.CRLF;
	$manifest .= '		</fieldset>'.CRLF;
	$manifest .= '</config>'.CRLF;

	return $manifest;
}
?>
